<?php
	require("wwdb.php");
	//wwdb();
	$myKey = cleanparam("sesskey");
	$gameID = cleanparam("gameID");
	
	//validate gameID
	if (validateGameID($gameID) != 2) {
		echo "Error with game ID";
		return;
	}
	
	//validate sesskey
	$memberID = validateKey($myKey);
	if ($memberID == null) {
		echo "Unrecognized session key!";
		return;
	}
	$result = mysql_query("SELECT * FROM gameStatus WHERE gameID=$gameID");
	$row = mysql_fetch_assoc($result);
	$playerCount = $row["playerCount"];
	//what turn number are we on?
	$result = mysql_query("SELECT * FROM lettersGuessed WHERE gameID=$gameID AND letter IS NOT NULL ORDER BY turnNumber DESC");
	if ($row = mysql_fetch_assoc($result)) {
		$turnNumber = $row["turnNumber"];
		$lastChooser = $row["memberID"];
		$lastLetter = $row["letter"];
		$result = mysql_query("SELECT * FROM lettersGuessed WHERE gameID=$gameID AND turnNumber=$turnNumber+1");
		if ($row = mysql_fetch_assoc($result)) $nextChooser = $row["memberID"];
		else $nextChooser = 0;
	}
	else {
		echo "Nothing to undo!";
		return;
	}
	//has everyone else placed the most recent letter?
	$result = mysql_query("SELECT * FROM waffle WHERE gameID=$gameID AND turnNumber=$turnNumber");
	$placedCount = mysql_num_rows($result);
	if ($placedCount == $playerCount && $nextChooser != $memberID) {
		echo "Too late to undo.  All " . $lastLetter . "s are placed.";
		return;
	}
	switch ($placedCount) {
	case 0:
		if ($lastChooser == $memberID) { //I chose it, ok to undo the last letter
			mysql_query("UPDATE lettersGuessed SET letter=NULL WHERE gameID=$gameID AND turnNumber=$turnNumber");
			echo 1;
		}
		else echo "Sorry, the next letter has already been chosen!";
		break;
	default:
		$result = mysql_query("SELECT * FROM waffle WHERE gameID=$gameID AND turnNumber=$turnNumber AND memberID=$memberID");
		if ($row = mysql_fetch_assoc($result)) { //ok to undo my last placement
			$xy = $row["x"] . $row["y"];
			$waffleID = $row["waffleID"];
			mysql_query("DELETE FROM waffle WHERE waffleID=$waffleID");
			echo $xy;
			break;
		}
		else echo "Sorry, somebody else has already placed $lastLetter.";
		break;
	}

?>